/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.system.bajlam.code.dao;

import com.system.bajlam.code.beans.QueryParameter;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author eliu
 */
@Stateless
public class PersistenceEjb implements Serializable {

    public static final int SINGLE = 1;
    public static final int LIST = 2;
    @PersistenceContext(name = "q")
    EntityManager em;

    public Object guardar(Object entidad) {
        em.persist(entidad);
        return entidad;
    }

    public void eliminar(Object entidad) {
        em.remove(em.merge(entidad));
    }

    public Object actualizar(Object entidad) {
        em.merge(entidad);
        return entidad;
    }

    /**
     *
     * @param namedQuery
     * @param params
     * @param type
     * @return
     */
    public Object doNamedQuery(String namedQuery, QueryParameter[] params, int type) {
        Query q = em.createNamedQuery(namedQuery);
        q.setHint("org.hibernate.cacheable", true);
        for (QueryParameter qp : params) {
            q.setParameter(qp.getKey(), qp.getValue());
        }
        switch (type) {
            case SINGLE:
                return q.getSingleResult();
            case LIST:
                return q.getResultList();
        }
        return null;
    }

    /**
     *
     * @param namedQuery
     * @param params
     * @param type
     * @return
     */
    public Object doJPAQuery(String namedQuery, QueryParameter[] params, int type) {
        Query q = em.createQuery(namedQuery);
        for (QueryParameter qp : params) {
            q.setParameter(qp.getKey(), qp.getValue());
        }
        q.setHint("org.hibernate.cacheable", true);
        switch (type) {
            case SINGLE:
                return q.getSingleResult();
            case LIST:
                return q.getResultList();
        }
        return null;
    }

    /**
     *
     * @param name
     * @param entity
     * @param params
     * @param unique
     * @return
     */
    public Object doSp(String name, Class entity, QueryParameter[] params, boolean unique) {
        Query q = em.createNativeQuery(name);
        for (QueryParameter qp : params) {
            q.setParameter(qp.getKey(), qp.getValue());
        }
        q.setHint("org.hibernate.cacheable", true);
        long timer = System.currentTimeMillis();

        if (unique) {
            Object r = entity.cast(q.getSingleResult());
            System.out.println("tiempo sec.= " + ( ( System.currentTimeMillis() - timer ) / 1000 ));
            return r;
        } else {
            List r = q.getResultList();
            System.out.println("tiempo sec.= " + ( ( System.currentTimeMillis() - timer ) / 1000 ));
            return r;
        }
    }
}
